在 Promise 的 then
方法中返回一个值,可以通过两种方式解决。
第一种方式是使用 return
关键字返回一个值,这个值将会被包装在一个新的 Promise 对象中。例如:
function asyncFunction() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello, World!');
}, 1000);
});
}
asyncFunction()
.then(result => {
console.log(result); // 输出:Hello, World!
return 'Returned from then'; // 在 then 方法中返回一个值
})
.then(returnValue => {
console.log(returnValue); // 输出:Returned from then
});
第二种方式是使用 Promise.resolve
方法返回一个包含要返回的值的 Promise 对象。例如:
function asyncFunction() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello, World!');
}, 1000);
});
}
asyncFunction()
.then(result => {
console.log(result); // 输出:Hello, World!
return Promise.resolve('Returned from then'); // 使用 Promise.resolve 返回一个 Promise 对象
})
.then(returnValue => {
console.log(returnValue); // 输出:Returned from then
});
无论使用哪种方式,返回的值都可以在后续的 then
方法中获取到。