如何解决从没有.then的承诺中提取价值
我想知道是否有一种方法可以获取promise的返回值并将其直接分配给.then()调用之外的变量并使用它?
这是我的实现方式。
const name = "Jane"
const age = 34
// Promise 1
function getName() {
return new Promise(function prom(resolve,reject) {
setTimeout(function () {
resolve(name) // "Jane"
},5000)
})
}
// Promise 2
function getAge() {
return new Promise(function prom(resolve,reject) {
setTimeout(function () {
resolve(age) // 34
},1500)
})
}
// Promise all
function getValue(cb) {
return Promise.all([
getName() /* Jane */,getAge() /* 34 */
])
.then(cb,cb)
}
在完成上述所有操作后,我尝试执行以下操作:
const x = getValue(x => x)[1] // 34
const sum = x + 1; // 35
有什么主意吗?还是有可能?
谢谢!
解决方法
您可以使用async / await以同步方式编写此代码,并降低代码的复杂性。异步/等待不是在promise上使用then(),而是提供了一种以同步方式编写异步代码的方法,而且很容易理解。
尝试使用以下替代代码:
const name = "Jane"
const age = 34
// Promise 1
function getName() {
return new Promise(function prom(resolve,reject) {
setTimeout(function () {
resolve(name) // "Jane"
},5000)
})
}
// Promise 2
function getAge() {
return new Promise(function prom(resolve,reject) {
setTimeout(function () {
resolve(age) // 34
},1500)
})
}
// Promise all
async function getValue() { /*To use await,function should start with async keyword*/
const userName = await getName(); /*Next line will not be executed until response is received here*/
const userAge = await getAge();
return Promise.all([
userName /* Jane */,userAge /* 34 */
])
}
async function main(){
const x =(await getValue())[1] // 34
const sum = x + 1; // 35
console.log(sum)
}
main()
请参考异步/等待主题以更好地理解此概念。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。