也许这个例子会对你有所帮助。
它展示了如何使用then 或async/await 来完成同样的事情。
// A new promise that will 'resolve' with the value 'Hello World!' after 1 second
const getResult = new Promise(resolveWithValue => {
setTimeout(() => {
resolveWithValue('Hello World!');
}, 1000);
});
function printResultUsingThen() {
getResult.then(result => {
console.log('Then:', result);
});
}
async function printResultUsingAwait() {
const result = await getResult;
console.log('Await:', result);
}
printResultUsingThen(); // prints "Then: Hello World!"
printResultUsingAwait(); // prints "Await: Hello World!"
编辑:在您的现场 cmet 之后,这里有一个更高级的示例。
我不是专家,所以我的 cmets 可能并不精确正确。
非常欢迎专家提供反馈。
// The program begins...
// The program makes this: A function that, after 1 second,
// will 'execute' (i.e. 'call', with parentheses) its argument, resolveWithValue,
// supplying 'Hello World!' as an argument to THAT execution.
// In other words,
// it will do resolveWithValue('Hello World!'), without knowing what it means.
const executorFunction = (resolveWithValue) => {
console.log(resolveWithValue.toString());
// prints "function () { [native code] }" to me
setTimeout(() => {
resolveWithValue('Hello World!');
}, 1000);
};
// The program makes this: A new promise that will internally generate a new function
// and pass that function's reference as an argument to executorFunction.
// When/if the interally generated function is called,
// this promise will resolve with the value that
// was passed to the interally generated function.
const getResult = new Promise(executorFunction);
// The program makes this: A function that has the capability of 'awaiting'.
// What 'async' practically means is that this function will return a promise.
const printResultUsingAwait = async () => {
const result = await getResult;
console.log('Await:', result);
let weirdMessage = 'It looks like this string is returned, ';
weirdMessage += 'but, actually, an internal promise has already been returned. ';
weirdMessage += 'That promise now resolves with THIS message.';
return weirdMessage;
}
// The program calls this function, storing the returned value in mysteriousVariable.
const mysteriousVariable = printResultUsingAwait();
console.log(mysteriousVariable); // prints "Promise { pending }"
// The program learns what it has to do when/if mysteriousVariable triggers
mysteriousVariable.then(whatIsThis => {
console.log('What is this?', whatIsThis);
console.log(mysteriousVariable); // prints "Promise { resolved }"
});
// The program is done, for now, and it is free to do other stuff,
// while it waits for something interesting to happen...
如果您可以在程序的根目录处使用await,您就不会让它转移到它必须做的其他事情上。程序本身不能是“承诺”。
(坦率地说,我真的不知道这些。也许它们不是 100% 正确的。这只是我迄今为止对语言的理解。)