javascript - Javascript 链接承诺
问题描述
我需要返回一个包含对象的承诺。我已经尝试过了,但我不确定这是否是正确的方法?
export const getCurrentLocation = async () => {
const currentLoc = {
code: null,
position: null,
watchId: null,
};
const promise = new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
(position) => {
currentLoc.code = 200;
currentLoc.position = position;
resolve(currentLoc);
},
(error) => {
console.log('Postion==err===>', error);
currentLoc.code = 400;
reject(currentLoc);
},
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
);
}).then(
new Promise((resolve, reject) => {
const watchId = navigator.geolocation.watchPosition();
currentLoc.watchId = watchId;
resolve(currentLoc);
}),
);
return promise;
};
在 Promise 块内我有异步功能
解决方案
您可以使用async/await:
const obj = {};
const populate = async() => {
await (() => obj.value1 = 'Deepak')();
await (() => obj.value2 = 'JavaScript')();
console.log(obj);
};
populate();
推荐阅读
- c - 为什么我的程序可以使用 for 但现在使用 while 循环?
- node.js - 为什么需要在 Linux 上才能在 Nodejs 上构建网站并做出反应?
- c# - 当我想获得输入时出现错误
- python-3.x - 尝试使用音乐数据进行迁移学习
- python - 如何在 python 3.8 中安装 opencv-python
- javascript - ReferenceError:“未定义 Swal”
- python - 在谷歌 colab 中从 spacy 中移出
- c++ - 数组何时自动初始化为其默认数据类型?
- python - 单调序列中的索引问题
- python - 如何创建一个新列,其值是现有 ByteArray 列的十六进制字符串?