Javascript 从没有.then()的承诺中提取值
我想知道是否有一种方法可以获取承诺的返回值,并将其直接赋给.then()调用之外的变量并使用它 这是我的实现Javascript 从没有.then()的承诺中提取值,javascript,asynchronous,promise,es6-promise,Javascript,Asynchronous,Promise,Es6 Promise,我想知道是否有一种方法可以获取承诺的返回值,并将其直接赋给.then()调用之外的变量并使用它 这是我的实现 const name = "Jane" const age = 34 // Promise 1 function getName() { return new Promise(function prom(resolve, reject) { setTimeout(function () { resolve(name)
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以同步方式编写此代码,并降低代码的复杂性。async/await提供了一种以同步方式编写异步代码的方法,也很容易理解,而不是在承诺中使用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()
请参阅async/await主题以更好地理解这个概念。提供了一些语法糖来实现这一点。await不能在异步函数的执行上下文之外使用!它可能在Deno中工作,因为Wait可以在顶级使用,但在vanilla JS中我不确定。除了“这感觉很奇怪,我想摆脱它”之外,还有什么特别的原因让你想知道吗?不,这是不可能的。你本质上是在问“有没有办法立即从未来获得价值?”。那是
承诺。所有调用都没有意义。@Bergi为什么不呢?因为承诺。所有都需要一系列承诺,但用户名和用户年龄都不是承诺。