我正在尝试编写一个方法来递归显示一个ActionSheetIOS来选择一个包含在数组中的值并返回所选的值:
async function _rescursiveSelect(data, index) {
if (index < data.length) {
const object = data[index];
if (object.array.length === 1) {
return await _rescursiveSelect(data, index + 1);
}
ActionSheetIOS.showActionSheetWithOptions({
title: 'Choose a value from array: ',
options: object.array,
},
buttonIndex => async function() {
const selectedValue = data[index].array[buttonIndex];
data[index].value = selectedValue;
delete data[index].array;
return await _rescursiveSelect(data, index + 1);
});
} else {
return data;
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,当我调用这个方法时,它会返回undefined.我想这个问题来自async/await使用,但我还没有计算它.
有什么建议吗?
我只是痛苦地意识到生成器函数不能用于等待.只有承诺或异步功能.
我的团队构建了一个完整的应用程序,所有模块都包含生成器函数,从主js文件调用一个Co模块.
除了通过数百个生成器功能并将它们更改function*(...){为async function(...){,还有什么方法可以使生成器与async/await一起工作?
没有任何意义,因为yield*/generators和async/await在处理流程方面非常相似,所以我想知道他们是如何错过等待支持生成器的.
我是Node的新手,并创建了一个具有async/await语法的应用程序,如下所示:
const express = require('express');
const app = express();
const someLibrary = require('someLibrary');
function asyncWrap(fn) {
return (req, res, next) => {
fn(req, res, next).catch(next);
};
};
app.post('/getBlock', asyncWrap(async (req,res,next) => {
let block = await someLibrary.getBlock(req.body.id);
[some more code]
}));
app.listen(process.env.PORT || 8000);
Run Code Online (Sandbox Code Playgroud)
它在我的机器上工作正常,但是当我部署到Heroku时,我收到错误,因为语法不受支持:
2017-03-23T10:11:13.953797+00:00 app[web.1]: app.post('/getBlock', asyncWrap(async (req,res,next) => {
2017-03-23T10:11:13.953799+00:00 app[web.1]: SyntaxError: Unexpected token (
Run Code Online (Sandbox Code Playgroud)
让Heroku支持这种语法的最简单方法是什么?
我成功地使用 onAuthStateChange 观察者检查用户的身份验证状态并将用户重定向到仪表板页面(react-native 项目)。但是,在仪表板上我已经想显示一些用户特定的数据,例如注册的程序/统计信息。为此,我需要初始化和填充 currentUser 对象,这需要一些时间(我需要从那里获取 uid 从数据库中获取一些数据)。因此,我正在寻找某种方法来等待此过程成功完成。我正在尝试在 componentDidMount 中使用 async/await 语法,但返回的结果为 null。(相同的语法在其他屏幕中成功运行,但在第一个屏幕中失败)
async componentDidMount() {
try {
let uid = await firebase.auth().currentUser.uid;
console.log(uid);
} catch(error) {
console.log(error);
}
}
Run Code Online (Sandbox Code Playgroud)
等待使用 async/await 语法加载 currentUser 对象的最佳方法是什么?我相信原因可能是 firebase 返回 null 作为第一个结果,然后更正 uid 作为第二个结果。
对于现在的解决方法,我使用简单的 setInterval 函数,但我不想增加太多加载时间。
let waitForCurrentUser = setInterval(() => {
if ( firebase.auth().currentUser.uid !== null ) {
clearInterval(waitForCurrentUser);
let uid = firebase.auth().currentUser.uid;
this.setState({uid});
return firebase.auth().currentUser.uid;
} else {
console.log('Wait for it');
}
}, 700);
Run Code Online (Sandbox Code Playgroud) javascript firebase react-native firebase-realtime-database ecmascript-2017
我正在使用karma-typescript以及此karma配置文件:
karmaTypescriptConfig: {
compilerOptions: {
target: "es5",
lib: ["dom", "es2015", "es2017"]
},
bundlerOptions: {
transforms: [require("karma-typescript-es6-transform")()]
}
},
Run Code Online (Sandbox Code Playgroud)
在我的规格文件中,我有以下代码:
import {} from './local/lib.js'
Run Code Online (Sandbox Code Playgroud)
在我的lib.js中,我有以下代码:
async function() {}
Run Code Online (Sandbox Code Playgroud)
使用执行测试时npm test,出现以下错误:
ERROR [source-reader.karma-typescript] Error parsing code: Unexpected token (X:Y) in /local/lib.js
Run Code Online (Sandbox Code Playgroud)
如果删除async关键字,一切都很好。
如何编辑我的业力配置文件以修复错误?
有没有一种方法可以使用TypeScript编译器仅删除类型注释,而不使用转译异步函数?有点像{ target: 'esInfinite' }选项吗?原因是:有些浏览器已经支持异步功能,因此我希望有一个不影响这些功能的构建目标。
输入示例:
async function foo(a : number) : Promise<void> {}
Run Code Online (Sandbox Code Playgroud)
示例输出:
async function foo(a) {}
Run Code Online (Sandbox Code Playgroud) 我有一些async我正在使用的功能,我有一个奇怪的问题.
我的代码,工作,看起来像:
async mainAsyncFunc (metadata) {
let files = metadata.map(data => this.anotherAsyncFunc(data.url));
return Promise.all(files);
}
Run Code Online (Sandbox Code Playgroud)
anotherAsyncFunc 功能看起来像:
async anotherAsyncFunc (url) {
return await axios({
url,
}).then(res => res.data)
.catch(err => {
throw err;
});
}
Run Code Online (Sandbox Code Playgroud)
当我尝试将更多数据附加到第一个函数(mainAsyncFunc)返回的内容时,我的问题出现了.我的想法是map自然地做到这一点,当所有的说完成时,修改它看起来像:
async mainAsyncFunc (metadata) {
files = metadata.map(data => {
return new Promise((resolve) => {
let file = this.anotherAsyncFunc(data.download_url);
let fileName = data.name;
resolve({
file,
fileName
});
});
});
return Promise.all(files);
}
Run Code Online (Sandbox Code Playgroud)
如果不清楚,我正常地获取文件,并向其附加一个fileName,然后重新解析该对象.
出于某种原因,这将返回一个挂起的Promise,而我希望它等待它们被完成,然后作为一个完整的文件和一个对象的名称返回.任何帮助了解我做错了什么都将非常感激.
我使用对象内的异步函数在express.js中发送响应
控制器代码:
module.exports = {
async signUpEmail(req, res) {
/**
* @description Parameters from body
* @param {string} firstName - First Name
* @inner
*/
const firstName = req.body.firstName;
res.send({ success: name });
throw new Error(); // purposely Done
}
}
Run Code Online (Sandbox Code Playgroud)
题:
由于signUpEmail方法在我的情况下是异步的,并且它将被拒绝,无论我的异步方法扔在这里它都来了Error.(故意放在那里)
所以记录在控制台中.
(node:13537) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error
(node:13537) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit …Run Code Online (Sandbox Code Playgroud) 如何捕获地理位置特定错误以通知用户他们必须打开地理位置?
catch记录了一个名为PositionError的错误,如Mozilla文档" https://developer.mozilla.org/en-US/docs/Web/API/PositionError "中所述.
*注意:我的代码没有捕获错误,它只显示:
Uncaught (in promise) ReferenceError: PositionError is not defined
Run Code Online (Sandbox Code Playgroud)
码
getCurrentLocation() {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject, {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
});
});
},
async inout() {
try {
let location = await this.getCurrentLocation();
let response = await axios.post(API.URL, {});
} catch (e) {
if(e instanceof PositionError) {
console.log('position error')
}
}
}
Run Code Online (Sandbox Code Playgroud) 我刚刚开始尝试类和异步等待。我使用的是 Node 版本 8.9.0 (LTS)。当 I 时console.log(this),我得到undefined而不是对对象的引用。
子处理程序.js
class Handler {
constructor(props) {
this.defaultRes = {
data: successMessage,
statusCode: 200
};
}
async respond(handler, reply, response = this.defaultRes) {
console.log(this); // why is `this` undefined????
try {
await handler;
return reply(response.data).code(response.statusCode)
} catch(error) {
return reply(error);
}
}
}
class SubHandler extends Handler {
constructor(props) {
super(props);
this.something = 'else';
}
makeRequest(request, reply) {
console.log(this); // why is `this` undefined!!
// in this case, doSomeAsyncRequest is …Run Code Online (Sandbox Code Playgroud) ecmascript-2017 ×10
javascript ×8
async-await ×7
node.js ×3
ecmascript-6 ×2
react-native ×2
babeljs ×1
express ×1
firebase ×1
geolocation ×1
hapijs ×1
heroku ×1
promise ×1
typescript ×1