We have this in our code:
const sqlUpsertRecommendations = recommendationsArray => {
// eslint-disable-next-line no-new
new Promise(resolve => {
const insertStatus = {
....
};
if (!recommendationsArray.length > 0) {
resolve({
error: false,
results: insertStatus,
localMessage: 'recommendationsArray.length = 0',
});
}
insertStatus.arrayEmpty = false;
dbConfig.transaction(txn => {
for (let i = 0; i < recommendationsArray.length; i++) {
const {
id,
recommendation_attribute,
recommendation_value,
segment_id,
target_attribute,
target_value,
is_deleted,
updated_at,
name,
image,
border_color,
} = recommendationsArray[i];
const params = [
id,
recommendation_attribute,
recommendation_value,
segment_id,
target_attribute,
target_value,
is_deleted,
updated_at,
name,
image,
border_color,
];
try {
txn.executeSql(
upsertRecommendations,
params,
(_tx, _results) => {
resolve({ error: false, results: insertStatus });
},
error => {
crashlytics().recordError(error);
if (__DEV__) {
console.log('sqlUpsertRecommendations error:', error);
}
const { notInserted } = insertStatus;
insertStatus.inserted = notInserted + 1;
if (1 + i === recommendationsArray.length) {
resolve({ error: false, ...error, results: insertStatus });
}
},
);
} catch (e) {
crashlytics().recordError(e);
}
}
});
});
};
I am learning async await and people in our team are using it like
const testFunction = async () => {
....
await sqlUpsertRecommendations(parsedData)
But vscode is saying
'await' has no effect on the type of this expression.
I just need idea how to best approach and use this kind of code?
You need to actually return
the new Promise
, then you can await
it. If you don't, you just start a Promise and then immediately return undefined
, and you can't await undefined
.
const sqlUpsertRecommendations = recommendationsArray => {
// eslint-disable-next-line no-new
return new Promise(resolve => {
// ... rest of code
async
is really just syntactic sugar for creating and using Promise
s. An async
function just returns a new Promise
and that's what await
cares about, so await
will work if you have a normal function that returns a Promise
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.