创建
Promise
和立即等待它的目的是什么?
async function foo() {
const x = await new Promise((resolve, reject) => { return resolve(5); });
console.log(x);
}
我认为创建一个
Promise
不可避免地与触发其调度的代码分离,不是吗?
根据 MDN 文档:
Promise 对象表示异步操作的最终完成(或失败)及其结果值。
我认为当您需要执行任务 B 并需要任务 A 中的数据时,等待 Promise 很重要,因此您需要等待任务 A 在任务 B 之前完成。例如
(async()=>{
let data='';
// without await and promise
data = fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => json);
console.log(data); // can't do next task, because data is empty
data = '';
// with await only
data = await fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => json);
console.log(data);
data = '';
// with promise only
data = new Promise((resolve,reject)=> {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => resolve(json))
.catch(e => reject(e));
});
console.log(data); // can't do next task, because data is empty
data = '';
// with await and promise
data = await new Promise((resolve,reject)=> {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => resolve(json))
.catch(e => reject(e));
});
console.log(data);
})();