【问题标题】:minimal introduction of promise async await? [closed]最低限度地引入承诺异步等待? [关闭]
【发布时间】:2020-02-17 00:36:41
【问题描述】:

我试图对 Promise、async 和 await 以及如何使用它们有一个快速和基本的了解。但是我还没有找到关于它们的最小教程。我看到的许多教程也使用了与 promise、async 和 await 不严格相关的东西。是否有任何最小的教程可以很好地解释它们?谢谢。

【问题讨论】:

  • something not strictly related to primise, async and await async/await 是 Promises 的“语法糖”——两者密不可分
  • 我猜你可以从MDN for using promises 开始。 async/await 在理解 promises 后应该会比较简单,因为它们只是语法糖,使用起来更容易。
  • 投票关闭的人请解释为什么应该关闭它。
  • 我在问一个 minimal 教程,根据定义,它不是自以为是的。请重新打开它。

标签: javascript node.js promise async-await


【解决方案1】:

也许这个例子会对你有所帮助。

它展示了如何使用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% 正确的。这只是我迄今为止对语言的理解。)

【讨论】:

  • 这是一个比许多冗长教程中的例子更好、更简洁的例子。所以await/async对基本上和Promise/then/catch的效果是一样的?
  • @user1424739 谢谢。这就是我写它的原因:P 是的。 async/await 只是让你的代码更扁平。等效于使用async/await 的catch 有一些……但你可以在花哨的教程中阅读它们(在你掌握了基础知识之后,IMO)。
  • 我在resolveWithValue('Hello World!'); 之前添加console.log(resolveWithValue);。然后,我在Then: Hello World! 之前看到[Function]。那是什么功能?
  • 另外,await 必须与async 一起使用吗?有没有办法只使用await 并查看其效果?
  • @user1424739 查看我的更新答案。
猜你喜欢
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-03
  • 2018-03-05
  • 1970-01-01
  • 2020-03-26
  • 2018-12-24
相关资源
最近更新 更多