简体   繁体   中英

ECMA 2015: how to use async functions with “yield” in a callback-routine?

In an ECMA-2015-App (concrete: React Native) using Redux and Redux-Saga we have constantly a huge usage of code like this (which works fine and is not really the issue here):

const stats = yield call([dataStorage, dataStorage.loadPrefetchingStats], languageId);

yield put({type: ACTIONS.R_SYNCHRONIZE_STATE_PROGRESS, payload: {max: statsUnfetched, value: statsFetched}});

try {
  yield importRecord(languageId, record, dataStorage)
}
catch(err) {
  console.log("ERROR: ", err)
  yield put({type: ACTIONS.R_SYNCHRONIZE_STATE_ERROR, payload: err});
  return false;
}

Short question here: is there - however - any possibility to combine async functions and yield-constructs within callback functions?

The longer question:

To work with a local sqlite-database on the users device we use this fantastic library react-native-sqlite-storage .

To encapsulate multiple sql-statements within a transaction, callbacks are necessary like this:

        this.db.transaction((tx) => {

            var sql = `UPDATE product SET prefetched=?, error_prefetching=0 WHERE id=?`;

            return tx.executeSql(sql, [
                product.prefetched,
                product.id
            ], (tx, results) => {
            }, (a, b) => {
                console.log('ERROR', a,b);
            }) ;

        });

It is well known and best practice to speed up sqlite on many many INSERTs or UPDATEs when all these statements are encapsulated within a large single transaction.

But since we are using redux with lots of "yield"-statements to communicate between business logic and UI-Updates, we have a problem now.

Has someone an idea here?

There is no way to handle callbacks in generators. The better method would be to Promisify your callbacks and then you could handle the promises using yields .

Consider a function that looks like this:

function doSomething(data,callback) {
   ...
   ...
   callback();
}

If you promisify it :

function promisedDoSomething(data) {
   return new Promise( (resolve) => {
      doSomething(data, resolve);
   }
}

Now you can use this promisified function in generators and just using it with yield .

var response = yield promisifiedDoSomething(data);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM