Anr*_*iki 0 javascript ecmascript-6
我知道要访问 Promise 的值,我将使用附加到它的“then”回调。
但是,我想知道如何影响它之外的上下文?
let outsideVar = 0;
promiseA.then(value => {
outsideVar = 1;
})
console.log(outsideVar); //0
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我想将 OutsideVar 更改为 1
[编辑]这个问题是为了看看promise是否可以影响它之外的全局变量,以及是否有可能做到这一点。
不幸的是,这是不可能的。
你的问题不是改变你的outsideVar,而是你检查得太早了。
这Promise是异步的,所以你需要等到它完成才能输出。
let outsideVar = 0;
promiseA.then(value => {
outsideVar = 1;
}).then(() => console.log(outsideVar));
Run Code Online (Sandbox Code Playgroud)
一旦开始使用 a Promise,您就需要继续编写异步代码。
如果您使用带有预设的 Babel 等预处理器,则可以使用await和。asynces2017
但它们也有一些注意事项:
async。这是示例:
let outsideVar = 0;
const doSomething = async () => {
await Promise.resolve(); // something that is async
outsideVar = 1;
};
await doSomething();
console.log(outsideVar);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
214 次 |
| 最近记录: |