How can I access the value of a promise?

要如何存取 promise 的結果?
https://stackoverflow.com/questions/29516390/how-can-i-access-the-value-of-a-promise

答案很簡單, 前面加 await, 或後面加 .then(function(result) { }); 就可以了. 真是太神奇了.


promiseA‘s then function returns a new promise (promiseB) that is immediately resolved after promiseA is resolved, its value is the value of what is returned from the success function within promiseA.

In this case promiseA is resolved with a value – result and then immediately resolves promiseB with the value of result + 1.

Accessing the value of promiseB is done in the same way we accessed the result of promiseA.

promiseB.then(function(result) {
    // here you can use the result of promiseB
});

As of ECMAScript 2016 (ES7, 2016), async/await is standard in JavaScript, which allows an alternative syntax to the approach described above. You can now write:

let result = await functionThatReturnsPromiseA();
result = result + 1;

Now there is no promiseB, because we’ve unwrapped the result from promiseA using await, and you can work with it directly.

However, await can only be used inside an async function. So to zoom out slightly, the above would have to be contained like so:

async function doSomething() {
    let result = await functionThatReturnsPromiseA();
    return result + 1;
}

And, for clarity, the return value of the function doSomething in this example is still a promise – because async functions return promises. So if you wanted to access that return value, you would have to do result = await doSomething(), which you can only do inside another async function. Basically, only in a parent async context can you directly access the value produced from a child async context.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *