logo
down
shadow

Can't return a promise chain with a catch block on the end


Can't return a promise chain with a catch block on the end

Content Index :

Can't return a promise chain with a catch block on the end
Tag : swift , By : Erwin
Date : November 29 2020, 04:01 AM

Hope this helps This used to work but with version 6 of PromiseKit this... , You just need to remove the catch block as below,
func checkIn(request: CheckinRequest) -> Promise<CheckinResponse> {
     let p = checkinService.checkIn(request: request)
          .then { r -> Promise<CheckinResponse> in
              return .value(r)
        }
      return p
}
extension Promise {

    func result() -> Guarantee<T> {
        return Guarantee<T>(resolver: { [weak self] (body) in
            self?.done({ (result) in
                body(result)
            }).catch({ (error) in
                print(error)
            })
        })
    }
}
let request = CheckinRequest()
checkinService.checkIn(request: request).result().done { response in
    // Check in response
}
checkinService.checkIn(request: request).result().then { (result) -> Promise<Bool> in
        // Use reuslt
        return .value(true)
    }.done { bool in
        print(bool)
    }.catch { (e) in
        print(e)
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to return from a Promise's catch/then block?


Tag : javascript , By : Barry
Date : March 29 2020, 07:55 AM
may help you . This can't be achieved with features of the language. However, pattern-based solutions are available.
Here are two solutions.
Promise.resolve()
.then(Function1).catch(errorHandler1)
.then(Function2).catch(errorHandler2)
.then(Function3).catch(errorHandler3)
.then(Function4).catch(errorHandler4)
.catch(finalErrorHandler);
function errorHandler1(error) {
    if (error instanceof MyCustomError) { // <<<<<<< test for previously thrown error 
        throw error;
    } else {
        // do errorHandler1 stuff then
        // return a result or 
        // throw new MyCustomError() or 
        // throw new Error(), new RangeError() etc. or some other type of custom error.
    }
}
Promise.resolve()
.then(function() { return Function1().catch(errorHandler1); })
.then(function() { return Function2().catch(errorHandler2); })
.then(function() { return Function3().catch(errorHandler3); })
.then(function() { return Function4().catch(errorHandler4); })
.catch(finalErrorHandler);

Promise: Ignore Catch and Return to Chain


Tag : javascript , By : CHeMoTaCTiC
Date : March 29 2020, 07:55 AM
seems to work fine Is it possible to ignore a catch and return back to the chain? , Here's the synchronous analogy:
try {
  action1(); // throws
  action2(); // skipped
  action3(); // skipped
} catch (e) {
  // can't resume
}
try {
  action1(); // throws
} catch (e) {
  handleError(e);
}
action2(); // executes normally
action3();
asyncActionA()        // <-- fails with 'missing' reason
.catch(error => {
   if(error.type == 'missing'){
      return; // Makes sure the promise is resolved, so the chain continues
   }
   throw error; // Otherwise, rethrow to keep the Promise rejected
})
.asyncActionB(promiseB) // <-- runs
.asyncActionC(promiseC)
.catch(err => {
  // Handle errors which are not of type 'missing'.
});

Promise catch() order in complex promise return chain


Tag : javascript , By : RichAA
Date : March 29 2020, 07:55 AM
To fix this issue When using promises, a function should do one of three things:
Return a value Return a promise Throw an error
function post() {
  foo.bar; // will throw
}

function run() {
  post()
    .then(log)
    .catch(log);
}
ReferenceError: foo is not defined
    at post (sync.js:6:3)
    at run (sync.js:10:3)
    at Object.<anonymous> (sync.js:15:1)
function post() {
  return new Promise((resolve, reject) => {
    reject('foo');
  });
}

function run() {
  post()
    .then(() => {})
    .catch((err) => {
      console.error('Caught error:', err);
    });
}
function post() {
  return new Promise((resolve, reject) => {
    resolve('foo');
  });
}

function run() {
  post()
    .then((result) => {
      throw result;
    })
    .catch((err) => {
      console.error('Caught error:', err);
    });
}

Throwing inside a catch block in a nested Promise to trigger the catch block of outer Promise, is there an alternative c


Tag : javascript , By : haver
Date : March 29 2020, 07:55 AM
Any of those help I think the clean way to do this would be using async/await. But before going there, is your question how to not run the outer promise when the inner promise fails?
The example below:
const fun42 = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() =>{
            resolve(42)
            reject('something at fun 42 went wrong')
        }, 500)
    })
}

const fun32 = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() =>{
            //resolve(32)
            reject('something at fun 32 went wrong')
        }, 500)
    })
}

fun32().then(x => {
    console.log(x)
    return fun42()
}).then( y => {
    console.log(y)
}).catch (e => {
    console.log(e)
})

Firebase Promise chain terminate in catch block


Tag : javascript , By : Josh
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Something like this should work, using a combination a propagated values and a top-level sentinel:
let bail = false

doWork()
.then(result => {
    console.log(result)
    return true  // indicate success
})
.catch(error => {
    console.error(error)
    return false  // indicate error
})
.then(isPriorSuccessful => {
    if (!isPriorSuccessful) {
        bail = true
        return null
    }
    else {
        // do more stuff here, return a promise
        return doMoreWork()
    }
})
.catch(error => {
    console.error(error)
})
.then(() => {
    if (bail) {
        res.status(500).send("NOT OK")
        return
    }
    console.log("Just before the end")
    res.send("OK")
})
Related Posts Related QUESTIONS :
  • Change frame of Live View in Swift playgrounds
  • Swift: Maintaining atomicity in a block-based execution using weak self
  • Why memory address is not changed for different instances of struct?
  • Filling a List in SwiftUI with CoreData
  • Kotlin Property Initialization (Like swift using closures)
  • Call a function from a separate class not working
  • Explanation of zip, reduce and combine in Swift
  • How to add a delay between loops when playing a tone in AVAudioPlayer?
  • How to add storyboard canvas orientation in git ignore in Xcode
  • How to execute different implementation of a method of a generic struct based on the generic type?
  • How to handle Errors on never ending chain with materialize?
  • RxSwift convert Observable<String> into String
  • Alamofire sending a request to an API 'NSInvalidArgumentException'
  • SwiftUI Conditional List - Unable to infer complex closure return type
  • Result values in '? :' expression have mismatching types 'String.SubSequence' (aka 'Substring') and 'String'
  • SwiftUI - Align contents of Button to the left
  • Swift handle did select on multiple annotations on same location
  • How to use NSPredicate for whether a List of Int contains a Int number?
  • SetNeedsDisplay having no effect
  • Can't initialize class with "if"
  • SKPaymentQueue.default().add(payment) ignored
  • How to share UIImage to Camera Roll using UIActivityViewController
  • Play Sound From String Arrays Swift
  • Runtime error using Combine: dyld: Symbol not found: _$s7Combine9PublishedV9PublisherCyx_GAadAMc
  • addPeriodicTimeObserver generate a escaping closure error
  • Since iOS 13 Beta 3, my app only displays a black window
  • showing uiview controller as a pop up
  • SwiftUI Beta 3 Black Screen
  • What is Content in SwiftUI?
  • How do I access the underlying key of a SymmetricKey in CryptoKit?
  • How to get dynamic Text height for a ScrollView with SwiftUI
  • SwiftUI: NavigationButton initializer gives error
  • How to limit character for username in Swift
  • How do I use UserDefaults with SwiftUI?
  • I'm an absolute beginner in swift. I don't what's wrong with the output of my code, This is based on mutating methods
  • How to reload data in UITableView when popping view controller
  • Cannot hook into another RxSwift stream based on a check
  • SwiftUI Change View with Button
  • SwiftUI: How to draw filled and stroked shape?
  • How to access inner object's properties from superclass without boilerplate
  • SwiftUI Table Custom Swipe?
  • Unwrapping optional inside map closure in Swift
  • What is the best way to wrap `purchaserInfo` for easy comparisons throughout your code using RevenueCat
  • How to shuffle multidimensional array?
  • Can you use a Publisher directly as an @ObjectBinding property in SwiftUI?
  • Changing certain words' colour in SCNText
  • Limit frequency with which firestore retrieves data
  • SwiftUI - Half modal?
  • Call a function multiple times and get a list of results in swift?
  • Open multiple preview same time in SwiftUI
  • What is simdTransform in SceneKit and ARKit?
  • How can I fill only part of the custom UIView rectangle?
  • Type of expression is ambiguous without more context in Xcode 11
  • How to setup Horizontal UICollectionView with paging, but items per page arrange from left to right & top to bottom
  • Why does this method with an optional parameter not override the base class method?
  • Implement a collection view SwiftUI
  • RealityKit – Set text programmatically of an Entity of Reality Composer
  • How to open file dialog with SwiftUI on platform "UIKit for Mac"?
  • Sliding one SwiftUI view out from underneath another
  • how to set a IBAction action on a button
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com