node.js - 在 Node.js 中返回一个 Promise
问题描述
我无法解决这个问题。
取以下三个函数 wherea
调用b
和b
调用c
:
const c = () => {
return new Promise( (resolve, reject) => {
setTimeout(() => {
resolve(new Date());
}, "1750");
});
};
const b = async () => {
const result = await c();
console.log("b(): %s", result);
return result;
};
const a = async () => {
const result = await b();
console.log("a(): %s",result);
return result;
};
console.log("Starting...");
const final_result = a();
console.log("Final Result: %s", final_result);
console.log("Ending...");
我希望b()
等待/获取由 . 返回的承诺的结果c()
,并将值传递给a()
. 然而,看起来 promise 被一路向上传递到调用堆栈。
为了获得我想要的行为,我必须处理每个函数中的承诺:
const c = () => {
return new Promise( (resolve, reject) => {
setTimeout(() => {
resolve(new Date());
}, "1750");
});
};
const b = async () => {
const result = await c();
console.log("b(): %s", result);
return result;
};
const a = async () => {
const result = await b();
console.log("a(): %s",result);
return result;
};
(async () => {
console.log("Starting...");
const final_result = await a();
console.log("Final Result: %s", final_result);
console.log("Ending...");
})()
为什么我不能只在一个函数中得到承诺的结果并返回呢?而且,如果我能做到,怎么做?
解决方案
推荐阅读
- reactjs - 如何提高 Material UI 整体动画速度
- python - 想知道 Scikit-Learn 中的编码算法
- java - 带有 sslSocketFactory 的 Okhttp.Builder 中的 ExceptionInInitializerError
- angular - 如何仅从 Angular 6 中的 http 请求中获取特定字段
- jquery - Jquery Append 不工作;“请删除换行符并编码小于字符...”在 F12 处引发错误
- python - 使用 Keras 对 3 个类进行图像分类仅返回一个值而不是 1 X 3 数组
- python - OpenCV 绘制轮廓错误断言失败
- android - 在 kotlin 中创建对象的语法有些模糊?
- codeigniter - 重定向时没有删除 index.php - codeigniter
- javascript - Vue prop - 在字符串中同时传递单引号和双引号