具有承诺

时间:2016-05-19 14:10:01

标签: javascript asynchronous promise react-native

我在react-native中有一个修改过的代码,用于从服务器获取数据,这很好。如果电话连接到互联网,我想添加NetInfo以便在获取之前始终检查。内在承诺是否可行?如何将此异步功能连接到我的代码?

'use strict';

var MAX_WAITING_TIME = 30000

var processStatus = function (response) {
    // status "0" to handle local files fetching (e.g. Cordova/Phonegap etc.)
    if (response.status === 200 || response.status === 0 || response.status === 201 || response.status === 422 || response.status === 302 ) {
        return Promise.resolve(response)
    } else if(response.status === 413) {
         return Promise.reject(alert(____mobile.connection_error.large_file))
    } else {
        //return Promise.reject(alert("Process status: "+JSON.stringify(response )))
        return Promise.reject(alert(____mobile.connection_error.top));
        console.log("Process status: "+JSON.stringify(response ));
    }
};

var parseJson = function (response) {
    return response.json();
};

var getWrappedPromise = function () {
    var wrappedPromise = {},
            promise = new Promise(function (resolve, reject) {
                wrappedPromise.resolve = resolve;
                wrappedPromise.reject = reject;
            });
    wrappedPromise.then = promise.then.bind(promise);
    wrappedPromise.catch = promise.catch.bind(promise);
    wrappedPromise.promise = promise;// e.g. if you want to provide somewhere only promise, without .resolve/.reject/.catch methods
    return wrappedPromise;
};

/* @returns {wrapped Promise} with .resolve/.reject/.catch methods */
var getWrappedFetch = function () {
    var wrappedPromise = getWrappedPromise();
    var args = Array.prototype.slice.call(arguments);// arguments to Array

    fetch.apply(null, args)// calling original fetch() method
        .then(function (response) {
            wrappedPromise.resolve(response);
        }, function (error) {
           // wrappedPromise.reject(alert("Fetch status: " + error));
            wrappedPromise.reject(____mobile.connection_error.top);
            console.log("Fetch status: " + error);
        })
        .catch(function (error) {
            wrappedPromise.catch(error);
        });
    return wrappedPromise;
};

/**
 * Fetch JSON by url
 * @param { {
 *  url: {String},
 *  [cacheBusting]: {Boolean}
 * } } params
 * @returns {Promise}
 */
var postJSON = function (params) {
    var headers1 = {}
    if (params.json){
        headers1 = {
            'Accept': 'application/json',
            'Content-Type': 'application/json'}
    } 

    if (params.headersIn){
        headers1 = params.headersIn
    }

   var methodTmp = 'POST'

    if (params.methodIn) {
        methodTmp = params.methodIn
    }
    console.log(methodTmp)
    var wrappedFetch = getWrappedFetch(
        params.cacheBusting ? params.url + '?' + new Date().getTime() : params.url,
        {
            method: methodTmp,//'POST',// optional, "GET" is default value
            headers: headers1,

            body: params.send_data
        });

    var timeoutId = setTimeout(function () {
        wrappedFetch.reject(alert(____mobile.connection_error.timeout, ____mobile.connection_error.check_connection));// reject on timeout
    }, MAX_WAITING_TIME);

    return wrappedFetch.promise// getting clear promise from wrapped
        .then(function (response) {
            clearTimeout(timeoutId);
            return response;
        })
        .then(processStatus)
        .then(parseJson);
};



module.exports = postJSON;

实现的最简单方法是什么:NetInfo.isConnected.fetch()这样获取只有在有互联网连接时才有效?

编辑: 我想用:

NetInfo.isConnected.fetch()

是的,我必须重写这段代码,不要使用getWrappedPromise,现在我认为是时候了。

EDIT2:好的,我重构了这段代码,希望它更好。任何评论欢迎。我测试过,我不确定我是否还需要这个NetInfo.isConnected.fetch()。现在没有错误没有连接或我错过了什么? 新代码:

var processStatus = function (response) {
    if (response == undefined) {
        return null
    }
    // status "0" to handle local files fetching (e.g. Cordova/Phonegap etc.)
    if (response.status === 200 || response.status === 0 || response.status === 201 || response.status === 422 || response.status === 302 ) {
        return Promise.resolve(response)
    } else if(response.status === 413) {
         return Promise.reject(alert(____mobile.connection_error.large_file))
    } else {
        //return Promise.reject(alert("Process status: "+JSON.stringify(response )))
        console.log("Process status: "+JSON.stringify(response ));
        return Promise.reject(alert(____mobile.connection_error.top));
    }
};

var parseJson = function (response) {
    if (response == undefined) {
        return null
    }
    return response.json();
};

var postJSON = function (params) {
    var headers1 = {}
    if (params.json){
        headers1 = {
            'Accept': 'application/json',
            'Content-Type': 'application/json'}
    } 

    if (params.headersIn){
        headers1 = params.headersIn
    }

   var methodTmp = 'POST'

    if (params.methodIn) {
        methodTmp = params.methodIn
    }
    console.log(methodTmp)

    var fetchPromise = fetch(params.cacheBusting ? params.url + '?' + new Date().getTime() : params.url,
        {
            method: methodTmp,//'POST',// optional, "GET" is default value
            headers: headers1,

            body: params.send_data
        })// calling original fetch() method
        .then(function (response) {
            return response;
        }, function (error) {
            console.log("Fetch status: " + error);
            return fetch
        }).then(processStatus)
        .then(parseJson);


    // timeoutId = setTimeout(function () {
    //     wrappedFetch.reject(alert(____mobile.connection_error.timeout, ____mobile.connection_error.check_connection));// reject on timeout
    // }, MAX_WAITING_TIME);

    return fetchPromise
};

0 个答案:

没有答案