我正在尝试异步异步尝试捕获块几天。
async function executeJob(job) {
// necessary variable declaration code here
try {
do {
let procedureRequests = await ProcedureRequestModel.find(filter, options);
// doing process here...
} while (fetchedCount < totalCount);
providerNPIIds = [...providerNPIIds];
// Fetch provider details
let providerDetails = await esHelper.getProvidersById(providerNPIIds, true);
try {
let updateProviderCount = await UserProvider.updateAll(
{
userId: userId
},
{
providers: providerNPIIds,
countByType: providerCountType
});
if(updateProviderCount) {
try {
let destroyJobId = await app.models.Job.destroyById(job.idd);
} catch (e) {
var err = new QueueError();
console.log(err instanceof …Run Code Online (Sandbox Code Playgroud) 通常,当涉及到 JavaScript 中async/ await 的错误处理时,人们默认使用try/ catch。但我想知道我是否可以使用.catch(),如
const res = await fetch().catch((error) => (
// error handling
));
const json = await res.json();
Run Code Online (Sandbox Code Playgroud)
try我想知道这是否与/catch块相同
try {
const res = await fetch()
const json = await res.json();
} catch(e) {
// error handling
}
Run Code Online (Sandbox Code Playgroud)
我知道从技术上讲try/catch块也可以捕获从中引发的错误res.json();,所以我想它仍然比示例更可取.catch()?
我对 async/await 很陌生,想知道使用 async/await 重构以下代码的最佳方法是什么?
export const createUser = (values, history) => {
return dispatch => {
axios.post('/api/signup', values)
.then(res => {
console.log('result', res);
}, rej => {
console.log('rejection', rej);
});
}
}
Run Code Online (Sandbox Code Playgroud)
当只提供一个参数时,.then对我来说非常简单,但是如果你有两个像这里这样的参数会发生什么?
我正在尝试处理我的方法引发的自定义错误async,但该try catch块无法正常工作。
我认为我这样做的方式应该有效,但错误没有被捕获,并且程序通过在终端中显示它来终止。
这是抛出错误的地方:
async setupTap(tap) {
const model = this.connection.model('Tap', TapSchema);
await model.findOneAndUpdate({ id: tap.id }, tap, (err, result) => {
let error = null;
if (!result) {
throw new Error('Tap doesn\'t exists', 404);
}
return result;
});
}
Run Code Online (Sandbox Code Playgroud)
然后是错误处理代码:
async setupTapHandler(request, h) {
const tapData = {
id: request.params.id,
clientId: request.payload.clientId,
beerId: request.payload.beerId,
kegId: request.payload.kegId,
};
try {
await this.kegeratorApi.setupTap(tapData);
} catch (e) {
if (e.code === 404) return h.response().code(404);
}
return h.response().code(204);
} …Run Code Online (Sandbox Code Playgroud) 我正在研究一个Angular 6应用程序,我被告知以下是一个反模式:
await someFunction().then(result => {
console.log(result);
});
Run Code Online (Sandbox Code Playgroud)
我意识到等待承诺链是毫无意义的.如果someFunction()返回一个promise,那么如果你正在等待它,则不需要一个promise链.你可以这样做:
const result = await someFunction();
console.log(result);
Run Code Online (Sandbox Code Playgroud)
但我被告知等待一个承诺链可能会导致错误,或者它会破坏我的代码中的东西.如果上面的第一个代码片段与第二个代码段完全相同,那么使用哪个代码片段至关重要.第一个片段引入了哪个危险,第二个片段没有?
我想要一些 JavaScript 代码将 3 个东西作为参数:
我最终做的是使用for循环。我不想使用递归函数:这样,即使有 50 次尝试,调用堆栈也不会长 50 行。
这是代码的打字稿版本:
/**
* @async
* @function tryNTimes<T> Tries to resolve a {@link Promise<T>} N times, with a delay between each attempt.
* @param {Object} options Options for the attempts.
* @param {() => Promise<T>} options.toTry The {@link Promise<T>} to try to resolve.
* @param {number} [options.times=5] The maximum number of attempts (must be greater than 0).
* @param {number} [options.interval=1] The interval …Run Code Online (Sandbox Code Playgroud) 我在JavaScript中有一个简单的代码,可以在API中执行请求并返回响应。但是在这种情况下,我将有成千上万的请求。因此,哪个代码选项会表现更好,为什么。另外,最近推荐哪一种作为好习惯?
第一种选择是使用.then来解决承诺,第二种选择是使用async / await。
在我的测试中,这两个选项的结果非常相似,没有显着差异,但是我不确定其范围。
// Using then
doSomething(payload) {
const url = 'https://link-here/consultas';
return this.axios.get(url, {
params: {
token: payload.token,
chave: payload.chave,
},
}).then(resp => resp.data);
}
// Using Async / await
async doSomething(payload) {
const url = 'https://link-here/consultas';
const resp = await this.axios.get(url, {
params: {
token: payload.token,
chave: payload.chave,
},
});
return resp.data;
}
Run Code Online (Sandbox Code Playgroud)
任何解释都将具有重大价值。
我很好奇 API 重试和超时应该如何实现。有时,仅仅等待 api 调用然后捕获出现的任何错误是不够的。如果我需要发出一系列异步请求,如下所示:
await client
.callA()
.then(async () => await callB())
.then(async () => await callC())
.catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)
如果其中一个承诺在中链失败,我想在几秒钟后再次尝试请求,直到尝试用完。
这是我尝试制作重试包装器。
async function retry (fn, undo, attempts, wait = 5000) {
await fn().catch(async (err) => {
console.error(err.message + `\n retrying in ${wait/1000} seconds...`);
if (attempts !== 0) {
// async timeout
await new Promise((resolve) => {
setTimeout(() => resolve(retry(fn, undo, attempts - 1)), wait);
})
} else {
await undo()
}
})
}
await retry(calls, undoCalls, 10)
Run Code Online (Sandbox Code Playgroud)
callA …
比较用户登录请求的密码。使用async 和 await等待获得实际响应。
我希望它按照以下顺序运行 1,2,3,4(console.log 的顺序)
但它执行为 1, 3, 4, 2. 请帮忙。
脚本不等待comparePassword
async login(request){
let response = await User.findOne({ email: request.email }, async (err, user) => {
if (err) throw err;
console.log('1');
let isMatch = await user.comparePassword(request.password, (err, isMatch) => {
console.log('2');
if (err) throw err;
request.isMatch = isMatch;
});
console.log('3');
return request;
});
console.log('4');
console.log('response', response);
}
Run Code Online (Sandbox Code Playgroud) async-await ×8
javascript ×8
node.js ×6
promise ×4
ecmascript-6 ×2
typescript ×2
asynchronous ×1
es6-promise ×1
mongoose ×1